﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using WeifenLuo.WinFormsUI.Docking;

using XEvents.Library;
using XEvents.Library.Targets;
using System.Diagnostics;

namespace ExtendedEventsManager
{
    public partial class MainForm : Form
    {
 
        private ServerExplorerForm m_solutionExplorer = new ServerExplorerForm();
        private ObjectExplorerDetailsForm m_objectExplorerDetails = new ObjectExplorerDetailsForm();
        private PropertiesForm m_propertiesForm = new PropertiesForm();
        private bool m_bSaveLayout = true;
        private DeserializeDockContent m_deserializeDockContent;
        internal Properties.Settings s = Properties.Settings.Default;

        public MainForm()
        {
            InitializeComponent();
            m_solutionExplorer = new ServerExplorerForm();
            m_deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString);
        }

        public ObjectExplorerDetailsForm Details
        {
            get { return m_objectExplorerDetails; }
        }
        public PropertiesForm PropertiesForm
        {
            get { return m_propertiesForm; }
        }
        public ServerExplorerForm ServerExplorer
        {
            get { return m_solutionExplorer; }
        }


        private IDockContent GetContentFromPersistString(string persistString)
        {
            if (persistString == typeof(ServerExplorerForm).ToString())
                return m_solutionExplorer;
            else if (persistString == typeof(ObjectExplorerDetailsForm).ToString())
                return m_objectExplorerDetails;
            else if (persistString == typeof(PropertiesForm).ToString())
                return m_propertiesForm;
            else 
                return null;
        }

        #region Menu Event Handlers
        private void menuItemSolutionExplorer_Click(object sender, System.EventArgs e)
        {
            m_solutionExplorer.Show(dockPanel);
        }
        private void objectExplorerDetailsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_objectExplorerDetails.Show(dockPanel);
        }
        private void propertiesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_propertiesForm.Show(dockPanel);
        }
        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_solutionExplorer.RefreshSelectedItem();
        }
        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewServerConnection();
        }
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (this.ActiveMdiChild != null)
                this.ActiveMdiChild.Close();
        }
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutForm a = new AboutForm();
            a.ShowDialog();
        }
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void extendedEventsInTheBooksOnlineToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("iexplore.exe", "http://technet.microsoft.com/en-us/library/bb630354.aspx");
        }

        #endregion 

        private void NewServerConnection()
        {
            ConnectionInfoForm ci = new ConnectionInfoForm();
            ci.Location = this.Location;
            ci.StartPosition = FormStartPosition.CenterScreen;

            DialogResult dr = ci.ShowDialog();

            if (dr == DialogResult.OK)
            {
                m_solutionExplorer.AddServer(ci.ServerInfo);
            }
        }


        private void MainForm_Load(object sender, System.EventArgs e)
        {
            string[] location = s.WindowLocation.Split(',');
            string[] size = s.WindowSize.Split(',');
            this.Location = new Point(Convert.ToInt32(location.ElementAt(0)), Convert.ToInt32(location.ElementAt(1)));
            this.WindowState = (FormWindowState)Enum.Parse(typeof(FormWindowState), s.WindowState);
            this.Size = new Size(Convert.ToInt32(size.ElementAt(0)), Convert.ToInt32(size.ElementAt(1)));

            string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "ExtendedEventsManager_Layout.xml");
 
            if (File.Exists(configFile))
                dockPanel.LoadFromXml(configFile, m_deserializeDockContent);
            else
                LayoutByCode();
        }

        private void LayoutByCode()
        {
            dockPanel.SuspendLayout(true);

            m_solutionExplorer.Show(dockPanel, DockState.DockLeft);
            m_objectExplorerDetails.Show(dockPanel, DockState.Document);
            m_propertiesForm.Show(dockPanel, DockState.DockRight);

            dockPanel.ResumeLayout(true, true);

        }

        public void OpenWithSSMS(string script)
        {
            string filename = Path.GetTempFileName();
            saveFileDialog1.FileName = filename + ".sql";
            System.IO.Stream s = saveFileDialog1.OpenFile();
            StreamWriter sw = new StreamWriter(s);
            sw.Write(script);
            sw.Flush();
            s.Flush();
            sw.Close();
            s.Close();

            Process.Start(saveFileDialog1.FileName);
        }

        public void CopyToClipboard(string script)
        {
            try
            {
                Clipboard.SetText(script);
            }
            catch
            {
                MessageBox.Show("An Exception Occured copying the script to the Clipboard.\r\n\r\nThis error occurs most often on Virtual machines with the vmusrvc.exe addin running.\r\nIf this problem persists, stop/kill this addin and try again.\r\nFor further information please see http://www.windowsvistaplace.com/clipboard-chaos/virtual-pc.", "Clipboard Failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void WriteTextToFile(string text)
        {
            saveFileDialog1.AddExtension = true;
            saveFileDialog1.DefaultExt = ".sql";

            DialogResult dr = saveFileDialog1.ShowDialog();
            if (dr != DialogResult.Cancel && saveFileDialog1.FileName != null && saveFileDialog1.FileName != string.Empty)
            {
                System.IO.Stream s = saveFileDialog1.OpenFile();
                StreamWriter sw = new StreamWriter(s);
                sw.Write(text);
                sw.Flush();
                s.Flush();
                sw.Close();
                s.Close();
            }
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            if (s.DisplayConnect)
                NewServerConnection();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (s.CloseWithOpenWarning)
            {
                if (this.dockPanel.DocumentsCount > 0)
                {
                    DialogResult dr = MessageBox.Show("You are about to close with open windows.\r\nAre you sure you want to do this?", "Exit Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dr == DialogResult.No)
                    {
                        e.Cancel = true;
                        return;
                    }
                }
            }

            s.WindowState = this.WindowState.ToString();
            s.WindowLocation = string.Format("{0},{1}", this.Location.X, this.Location.Y);
            s.WindowSize = string.Format("{0},{1}", this.Size.Width, this.Size.Height);
            s.Save();

            string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "ExtendedEventsManager_Layout.xml");
            if (m_bSaveLayout)
                dockPanel.SaveAsXml(configFile);
            else if (File.Exists(configFile))
                File.Delete(configFile);

        }

        private void extendedEventManagerOptionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OptionEditorForm oef = new OptionEditorForm();
            oef.ShowDialog();
            //oef.Show(dockPanel, DockState.Float);
        }

    }
}
